/**
 * Credits to: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
 */
package studyspots.feup;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * Cliente REST
 *
 */
public class RestClient {

   private static String convertStreamToString(InputStream is) {
       /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
       BufferedReader reader = new BufferedReader(new InputStreamReader(is));
       StringBuilder sb = new StringBuilder();

       String line = null;   
       try {
           while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }

   /* This is a test function which will connects to a given
    * rest service and prints it's response to Android Log with
    * labels "Praeda".
    */
   public static Spot[] getSpots(String url)
   {
	   
	   Spot spots[] = null;
	   
       HttpClient httpclient = new DefaultHttpClient();

       // Prepare a request object
       HttpGet httpget = new HttpGet(url); 

       // Execute the request
       HttpResponse response;
       try {
           response = httpclient.execute(httpget);
           // Examine the response status
           Log.i("JSON",response.getStatusLine().toString());

           // Get hold of the response entity
           HttpEntity entity = response.getEntity();
           // If the response does not enclose an entity, there is no need
           // to worry about connection release

           if (entity != null) {

               // A Simple JSON Response Read
               InputStream instream = entity.getContent();
               String result= convertStreamToString(instream);
               Log.i("JSON",result);
               
               
               
       			JSONArray jsonArray = new JSONArray(result);
       			Log.i("JSON", "Number of entries " + jsonArray.length());
       			
       			spots = new Spot[jsonArray.length()];
       			
       			
       			for (int i = 0; i < jsonArray.length(); i++) {
       				JSONObject jsonObject = jsonArray.getJSONObject(i);
       				
       				spots[i] = new Spot();
       				spots[i].local = jsonObject.getString("local");
       				spots[i].id = jsonObject.getString("spot_id");
       				Log.i("JSON", spots[i].local + " " + spots[i].id);
       				
       			}
               instream.close();
           }


       } catch (ClientProtocolException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
    	   Log.i("JSON", "Problem reaching site.");
           // TODO Auto-generated catch block
           e.printStackTrace();
       } 
           catch (JSONException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       
       return spots;
   }

   
   public static String[] getStudents(String url)
   {
	   
	   String lv_arr[] = null;
	   
       HttpClient httpclient = new DefaultHttpClient();

       // Prepare a request object
       HttpGet httpget = new HttpGet(url); 

       // Execute the request
       HttpResponse response;
       try {
           response = httpclient.execute(httpget);
           // Examine the response status
           Log.i("JSON",response.getStatusLine().toString());

           // Get hold of the response entity
           HttpEntity entity = response.getEntity();
           // If the response does not enclose an entity, there is no need
           // to worry about connection release

           if (entity != null) {

               // A Simple JSON Response Read
               InputStream instream = entity.getContent();
               String result= convertStreamToString(instream);
               Log.i("JSON",result);
               
               /*if(result.contains("[null]")){
            	   Log.i("JSON", "null received");
            	   return null;

               }*/
               
       			JSONArray jsonArray = new JSONArray(result);
       			Log.i("JSON", "Number of entries " + jsonArray.length());
       			
       			lv_arr = new String[jsonArray.length()];
       			
       			
       			for (int i = 0; i < jsonArray.length(); i++) {
       				JSONObject jsonObject = jsonArray.getJSONObject(i);
       				
       				lv_arr[i] = jsonObject.getString("email");
       				Log.i("JSON", lv_arr[i]);
       				
       			}
               instream.close();
           }


       } catch (ClientProtocolException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
    	   Log.i("JSON", "Problem reaching site.");
           // TODO Auto-generated catch block
           e.printStackTrace();
       } 
           catch (JSONException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       
       return lv_arr;
   }
}
